<template>
    <div class="rule-main" :class="{ 'rule-main-not': isDisabled }">
        <div class="rule-main-content">
            <el-form :model="form" :rules="rules" ref="formRef">
                <h1>积分获取规则</h1>
                <el-form-item prop="switch" class="switch-form">
                    <el-checkbox
                        v-model="form.switch"
                        @change="switchChange"
                        :true-label="1"
                        :false-label="2"
                        :disabled="isDisabled"
                        >按照订单商品实际金额，赠送积分</el-checkbox
                    >
                    <span class="rule-scrm-header" v-if="isScrm"
                        >（商城端购物赠积分的规则已失效，将按照scrm端的积分获取规则统一计算。）</span
                    >
                    <div style="width: 100%; margin: 20px 0" v-if="form.switch == 1">
                        每单购买金额每满<el-input-number
                            v-model="form.perGroupAmount"
                            :disabled="isDisabled"
                            class="custom-number-small"
                            :min="0"
                            :max="99999999"
                            :precision="0"
                            :controls="false" />元，赠送<el-input-number
                            v-model="form.producerPoints"
                            :disabled="isDisabled"
                            class="custom-number-small"
                            :min="0"
                            :max="99999999"
                            :precision="0"
                            :controls="false" />积分
                    </div>
                </el-form-item>
                <SpecialDialog class="custom-btn-dialog" v-if="form.switch == 1" :disabled="isDisabled"></SpecialDialog>
                <h1>积分消耗规则</h1>
                <el-form-item class="custom-point-form-item" prop="points">
                    1元=<el-input-number
                        v-model="form.points"
                        :disabled="isDisabled"
                        class="custom-number-small"
                        :min="1"
                        :max="99999999"
                        :precision="0"
                        :controls="false" />积分
                </el-form-item>
                <el-form-item>
                    <div>
                        积分抵现
                        <el-switch
                            class="custom-switch"
                            v-model="form.isOn"
                            :disabled="isDisabled"
                            :active-value="1"
                            :inactive-value="2"
                            @change="isOnChange" />
                    </div>
                    <template v-if="form.isOn == 1">
                        <el-form-item class="custom-form-item" label="可抵扣比例：">{{ form.deduction }}%</el-form-item>
                        <el-form-item class="custom-form-item" label="适用商品：" prop="suitGoods">
                            <el-radio-group :disabled="isDisabled" v-model="form.suitGoods" @change="suitGoodsChange">
                                <div class="activity-good-type" v-for="item in activityGoodTypes" :key="item.value">
                                    <el-radio :label="item.value">
                                        {{ item.label }}
                                    </el-radio>
                                    <ChoosePointGood
                                        style="margin-left: -14px"
                                        :disabled="isDisabled"
                                        v-if="item.value != 1 && form.suitGoods == item.value"
                                        :value="form.selectedGoods"
                                        :isMulti="true"
                                        @handle-confirm="getGoodData" />
                                    <SelectedGoodDialog
                                        :disabled="isDisabled"
                                        v-if="item.value != 1 && form.suitGoods == item.value"
                                        :value="form.selectedGoods"
                                        @handle-remove="handleRemoveGood" />
                                </div>
                            </el-radio-group>
                        </el-form-item>
                    </template>
                </el-form-item>
            </el-form>
            <div class="form-footer" v-if="!isDisabled">
                <el-button type="primary" @click="saveHandler">保存</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import { onUnmounted, onMounted, reactive, ref, unref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { isDayBefore, dateDiff, cloneDeep, format } from '@/commons/utils';
import request from '@/request/index';
import { setLayout, resetLayout } from '@/hooks/layout';
import SpecialDialog from './specialDialog.vue';
import ChoosePointGood from './choosePointGood.vue';
import SelectedGoodDialog from './selectedGoods.vue';
import { debounce } from 'lodash';
import store from '@/store/index';

const useAuth = store.useAuthStore();
const permissions = useAuth.permissions;
// 积分规则编辑point_rule:edit 积分商城编辑point_mail:edit 积分设置编辑point_base:edit
const isDisabled = computed(() => {
    return !permissions.has('point_rule:edit');
});

const activityGoodTypes = [
    { value: 1, label: '全部商品参与' },
    { value: 2, label: '指定商品参与' },
    { value: 3, label: '指定商品不参与' }
];

const isScrm = ref(false);
const form = reactive({
    status: null,
    authScrm: 1,
    switch: null,
    points: 100,
    perGroupAmount: null,
    producerPoints: null,
    isOn: 2,
    deduction: 100,
    suitGoods: 1,
    selectedGoods: []
});
const formRef = ref();
const checkActivityAt = () => {};
const checkSwitch = (rule, val, callback) => {
    if (val === 1 && (form.perGroupAmount === null || form.perGroupAmount === null)) {
        return callback('请输入金额和积分');
    }
    callback();
};
const checkPoints = (rule, val, callback) => {
    if (!val) {
        return callback('积分必须为正整数');
    }
    callback();
};
const checkGoods = (rule, value, callback) => {
    if ([2, 3].includes(form.suitGoods) && !form.selectedGoods?.length) {
        return callback(new Error(`指定商品${form.suitGoods == 3 ? '不' : ''}参与，必须选择商品`));
    }
    callback();
};
const rules = reactive({
    activityName: [
        { required: true, message: '请输入活动名称', trigger: 'blur' },
        { max: 20, message: '最长不超过20个字', trigger: 'blur' }
    ],
    switch: [{ required: true, trigger: 'blur', validator: checkSwitch }],
    points: [{ required: true, trigger: 'blur', validator: checkPoints }],
    suitGoods: [{ required: false, validator: checkGoods, trigger: 'change' }]
});

const switchChange = val => {
    // 切换
    if (val == 1) {
        form.perGroupAmount = 0;
        form.producerPoints = 0;
    } else {
        clearValidate('switch');
        form.perGroupAmount = null;
        form.producerPoints = null;
    }
};

const saveHandler = debounce(async () => {
    if (!unref(formRef)) return;
    await unref(formRef).validate(async (valid, fields) => {
        if (valid) {
            const { code } = await request('pointsSaveConfig', {
                authScrm: form.authScrm,
                pointProducer: [
                    {
                        name: 'order_amount',
                        config: {
                            switch: form.switch,
                            perGroupAmount: form.perGroupAmount !== null ? Math.round(form.perGroupAmount * 100) : null,
                            producerPoints: form.producerPoints !== null ? Math.round(form.producerPoints * 100) : null
                        }
                    }
                ],
                pointConsumer: [
                    {
                        name: 'point_consumer',
                        config: {
                            rmb: 100,
                            points: form.points !== null ? Math.round(form.points * 100) : null
                        }
                    }
                ],
                pointGoodsMail: {
                    status: form.status
                },
                pointDeduction: {
                    isOn: form.isOn,
                    deduction: form.deduction !== null ? Math.round(form.deduction * 100) : null, //可抵扣比例
                    suitGoods: form.suitGoods, //适用商品类型 1全部商品参与，此时selectedGoods 传递为空 2 部分商品参与 3 部分商品不参与
                    selectedGoods: form.selectedGoods
                }
            });
            if (code !== 0) {
                return;
            }
            ElMessage({
                type: 'success',
                message: '积分规则保存成功'
            });
        } else {
            unref(formRef).scrollToField(Object.keys(fields)?.[0]);
        }
    });
}, 500);

const getGoodData = data => {
    form.selectedGoods.length = 0;
    Object.assign(form.selectedGoods, cloneDeep(data));
};
const handleRemoveGood = id => {
    form.selectedGoods.splice(form.selectedGoods.indexOf(id), 1);
    validateField('suitGoods');
};
const suitGoodsChange = val => {
    if (val == 1) {
        form.selectedGoods.length = 0;
    }
    validateField('suitGoods');
};

const isOnChange = val => {
    if (val == 2) {
        form.selectedGoods.length = 0;
        form.suitGoods = null;
        return;
    }
    form.suitGoods = 1;
};

const clearValidate = field => {
    unref(formRef).clearValidate(field);
};

const validateField = field => {
    unref(formRef).validateField(field);
};

const getDetail = async () => {
    const { data } = await request('pointsConfig');
    const { perGroupAmount, producerPoints, switch: isSwitch } = data?.pointProducer?.[0]?.config || {};
    form.perGroupAmount = perGroupAmount !== null ? perGroupAmount / 100 : null;
    form.producerPoints = producerPoints !== null ? producerPoints / 100 : null;
    form.points = (data?.pointConsumer?.[0]?.config?.points || 10000) / 100;
    form.status = data?.pointGoodsMail?.status;
    form.authScrm = data?.pointGoodsMail?.auth_Scrm;
    form.switch = isSwitch;
    form.isOn = data?.pointDeduction?.isOn;
    form.deduction = (data?.pointDeduction?.deduction || 10000) / 100;
    form.suitGoods = data?.pointDeduction?.suitGoods;
    form.selectedGoods = data?.pointDeduction?.selectedGoods || [];
};

const getFollowRuleServ = async () => {
    let params = {
        rule: 1
    };
    let res = await request('getFollowRuleServ', params);
    const type = res?.data?.levelFollow;
    isScrm.value = type == 2;
};

onMounted(() => {
    getFollowRuleServ();
    getDetail();
    setLayout('custom-rule-lay-layout');
});
onUnmounted(() => {
    resetLayout('custom-rule-lay-layout');
});
</script>

<style lang="scss">
.custom-rule-lay-layout {
    padding: 0 !important;
}
</style>
<style lang="scss" scoped>
.rule-main {
    position: relative;
    min-height: calc(100vh - 190px);
    &-content {
        overflow-y: auto;
        max-height: calc(100vh - 240px);
        padding: 24px;
    }
    :deep {
        .el-form-item__content {
            padding-left: 20px;
        }
    }
    .rule-scrm-header {
        color: var(--el-color-primary);
    }
    .custom-btn-dialog {
        padding-left: 20px;
        margin-top: -15px;
    }
    h1 {
        font-size: 14px;
        font-weight: 500;
        position: relative;
        padding-left: 15px;
        margin: 20px 0;
        &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 15%;
            width: 3px;
            height: 70%;
            background-color: var(--el-color-primary);
        }
    }
    .switch-form {
        :deep {
            .el-form-item__error {
                margin-top: -18px;
                padding-left: 20px;
            }
        }
    }
    .custom-number-small {
        width: 80px;
        margin: 0 4px;
    }
    .custom-point-form-item {
        :deep.el-form-item--default .el-form-item__error {
            padding-left: 20px;
        }
    }
    .custom-deduction {
        width: 100%;
    }
    .custom-form-item {
        width: 100%;
        :deep {
            .el-form-item__label {
                justify-content: flex-start;
                width: 85px;
                color: initial;
                padding-right: 0;
            }
            .el-form-item__content {
                padding-left: 0;
            }
        }
    }
    .activity-good-type {
        display: flex;
        align-items: center;

        width: 100%;
    }
    .form-footer {
        position: absolute;
        display: flex;
        align-items: center;
        justify-content: center;
        width: calc(100% + 31px);
        height: 70px;
        background-color: #fff;
        bottom: -64px;
        left: -15px;
        box-shadow: 0px 0px 10px 0px rgb(212 212 212 / 50%);
        border-radius: 2px;
        z-index: 1;
        .el-button {
            width: 80px;
        }
    }
}
.rule-main-not {
    min-height: calc(100vh - 145px);
}
</style>
